package com.customer.controller.user;

import com.customer.dto.UserLoginDTO;
import com.customer.dto.UserRegisterDTO;
import com.customer.dto.UserUpdateDTO;
import com.customer.mapper.UserMapper;
import com.customer.result.Result;
import com.customer.service.UserService;
import com.customer.constant.JwtClaimsConstant;
import com.customer.constant.MessageConstant;
import com.customer.entity.User;
import com.customer.exception.LoginFailedException;
import com.customer.properties.JwtProperties;
import com.customer.utils.JwtUtil;
import com.customer.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController("userUserController")
@RequestMapping("/user/user")
@Slf4j
@Api(tags = "用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 账号密码登录
     *
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("账号密码登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("账号密码登录：{}", userLoginDTO);

        // 使用UserService进行登录验证
        User user = userService.login(userLoginDTO);

        // 验证用户是否存在
        if (user == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    /**
     * 用户注册
     *
     * @param userRegisterDTO
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result register(@RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("用户注册：{}", userRegisterDTO);

        // 检查用户名是否已存在
        try {
            User existingUser = userMapper.getByUsername(userRegisterDTO.getUsername());
            if (existingUser != null) {
                return Result.error("用户名已存在");
            }
        } catch (Exception e) {
            log.warn("检查用户名是否存在时出错：{}", e.getMessage());
        }
        // 检查密码和确认密码是否一致
        if (!userRegisterDTO.getPassword().equals(userRegisterDTO.getRePassword())) {
            return Result.error("密码和确认密码不一致");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(userRegisterDTO.getUsername());
        user.setPassword(userRegisterDTO.getPassword());

        // 设置其他默认值
        user.setCreateTime(LocalDateTime.now());

        // 保存用户
        userMapper.insert(user);

        return Result.success();
    }

    /**
     * 退出登录
     */
    @PutMapping("/logout")
    @ApiOperation("退出登录")
    public Result logout() {
        log.info("退出登录");
        return Result.success();
    }

    /**
     * 修改用户信息
     *
     * @param userUpdateDTO
     * @return
     */
    @PutMapping
    @ApiOperation("修改用户信息")
    public Result update(@RequestBody UserUpdateDTO userUpdateDTO) {
        log.info("修改用户信息：{}", userUpdateDTO);
        userService.update(userUpdateDTO);
        return Result.success();
    }

    /**
     * 根据用户id查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据用户id查询用户信息")
    public Result getById(@PathVariable Long id) {
        log.info("查询用户信息,{}", id);
        User user = userService.getById(id);
        return Result.success(user);
    }
}
